<?php

namespace app\api\service;

use app\common\model\goods\GoodsProductModel;
use app\common\model\user\UserCartModel;

class GoodsService
{

    public static function goods_find($type = 0)
    {
        if ($type == 0) return ['id,imgs,name,tags,browse,cart,buy'];
        if ($type == 1) return ['id,imgs,name,tags,intro,details,browse,cart,buy,type,link'];
    }

    public static function handle_cart($uid)
    {
        $list = UserCartModel::where('user_id', $uid)->field('id,goods_id,goods_product_id,quantity')->select()->toArray();
        foreach ($list as $item) {
            $condition = ['status' => 1];
            $goodsProduct = GoodsProductModel::where('id', $item['goods_product_id'])
                ->field('price,line_price,img,name,stock,status')->find();
            if ($goodsProduct) {
                if ($goodsProduct['status'] != 1) {
                    $condition = ['status' => 3, 'check' => 0];
                } else if ($goodsProduct['stock'] <= 0) {
                    $condition = ['status' => 2, 'check' => 0];
                } else if ($goodsProduct['stock'] >= $item['quantity']) {
                    $condition = ['status' => 1, 'quantity' => $item['quantity']];
                }
                UserCartModel::where('id', $item['id'])->update($condition);
            } else {
                UserCartModel::where('id', $item['id'])->delete();
            }
        }
        return true;
    }

    public static function cart_status($status)
    {
        if ($status == 2) {
            $content = '补货中';
        } else if ($status == 3) {
            $content = '已下架';
        }
        return $content ?? '';
    }
}
